import '../common/style.less';
import { IOneModalRef } from '@/pages/type';
import { OneModal } from '@/components/one-ui';
import pageStyles from '@/common/pageLayout.less';
import InfiniteScroll from 'react-infinite-scroller';
import { ApplyManageService } from '../services/ManageService';
import { ApplyUpdateService } from '../services/UpdateService';
import { SearchOutlined } from '@ant-design/icons';
import { MothedChangeColumns } from '../mconfig/MothedChangeColumns';
import { getTenantID, loopArray, tooltipLength } from '@/utils';
import React, { Key, Ref, SetStateAction, useEffect, useMemo, useRef, useState } from 'react';
import { AutoComplete, Card, Col, Empty, Input, Row, Spin, Table, Tooltip, Tree, TreeProps, message } from 'antd';
import MyIcon from '@/components/MyIcon';
import { ILoadMapTypeAll } from '@/common';

export const SelectProjectModal = ({ onSave, onClose, curRes }) => {
  const projectRef: Ref<IOneModalRef> = useRef(null); /** 弹框Ref */
  const prefixCls = 'pack-selectproject';
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]); /** 表格选中行的key */
  const [selectedRows, setSelectedRows] = useState<Record<string, any>[]>([]); /** 表格选中行内容 */
  const [tableDataSource, setTableDataSource] = useState<Record<string, any>[]>([]); /** 表格渲染数据 */

  /** 左侧项目接口 */
  const { getProjectService } = ApplyUpdateService();
  const { getProjectRun, getProjectLoading, getProjectPagination, ProjectData } = getProjectService();

  // const {
  //   applyManageRun,
  //   applyManageDataSource,
  //   applyManageLoading,
  //   applyManageTableProps
  // } = ApplyManageService(curRes, { state: `${getTenantID()}${ILoadMapTypeAll?.PURAPPLY_STATE}1000` }).getApplyManageService(20);

  /** 获取标包接口 */
  const { getPackRun, getPackLoading } = ApplyUpdateService()?.getPackService();

  /** 封装获取标包接口方法 */
  const fetchGetPack = async (ids) => {
    let { msgFlag, msg, obj } = await getPackRun({ packIds: ids });
    if (msgFlag) {
      message?.success(msg);
      setTableDataSource(obj);
    }
  };

  /** 弹窗确定事件 */
  const onConfirm = () => {
    // if (selectedRows?.length) {
    //   let row = selectedRows[0];
    //   const result = applyManageDataSource?.find((item) => {
    //     if (item?.mpurchasePacks?.length) {
    //       return item?.mpurchasePacks?.find((item) => {
    //         return item?.id === row?.id;
    //       });
    //     }
    //   });
    //   onSave({ applyInfo: result, packInfo: row });
    //   onCloseModalCommon(projectRef);
    // } else {
    //   message?.warn('请选择标包后再保存！');
    // }
  };

  // projectCode 项目编号
  // projectName 项目名称
  // projectSum 项目费用（元）

  /** <<<====================左侧START========================>>> */
  // 左侧类型树搜索
  const [typeTreeSearchObj, setTypeTreeSearchObj] = useState<Record<string, any>>({
    searchValue: '',
    expandedKeys: [],
  });
  const [selectKeys, setSelectKeys] = useState<React.Key[]>([]); /** 左侧选中树的key */

  // 自动完成组件options
  const autoCompleteOptions = useMemo(() => {
    let option: Record<string, any>[] = [];
    const tileTreeData = (data: Record<string, any>[]) => {
      data?.forEach((item) => {
        const name = item?.projectName;
        if (name?.includes(typeTreeSearchObj?.searchValue)) {
          const nameLength = name?.length;
          const select = name?.search(typeTreeSearchObj?.searchValue);
          const searchLength = typeTreeSearchObj?.searchValue?.length;
          const afterStr = name?.slice(0, select);
          const selectStr = typeTreeSearchObj?.searchValue;
          const beforeStr = name?.slice(select + searchLength, nameLength);
          option.push({
            value: name,
            key: item?.mockID,
            label: (
              <div>
                <span>{afterStr}</span>
                <span style={{ color: '#f50' }}>{selectStr}</span>
                <span>{beforeStr}</span>
              </div>
            ),
            itemrowobj: { ...item },
          });
        } else {
          option.push({
            value: name,
            key: item?.mockID,
            label: (
              <div>
                <span>{name}</span>
              </div>
            ),
            itemrowobj: { ...item },
          });
        }
      });
    };
    tileTreeData(ProjectData);
    return option;
  }, [ProjectData, typeTreeSearchObj?.searchValue]);

  /** 自动完成组件的事件 */
  const onAutoSelectLeft = (value: string, option: any) => {
    const optionId = option?.itemrowobj?.projectCode;
    const targetNode = loopArray(ProjectData)?.find((i) => i?.projectCode == optionId);

    const searchObj: Record<string, any> = {
      searchValue: value,
      expandedKeys: [targetNode?.projectCode],
    };

    setTypeTreeSearchObj(searchObj);
    setSelectKeys([optionId]);

    if (option?.packIDs) {
      fetchGetPack(option?.packIDs); //获取标包
    }
  };

  /** 搜索框的事件 */
  const onInputChange = (ev: Record<string, any>) => {
    setTypeTreeSearchObj({
      ...typeTreeSearchObj,
      searchValue: ev?.target?.value,
    });
  };

  /** 点击item获取对象 */
  const onChangeSelect = (selectedKeys: SetStateAction<Key[]>, info) => {
    const selectedKey = [info?.node?.projectCode];
    if (selectedKey?.length) {
      setSelectKeys(selectedKey);
      // if (info?.node?.packIDs) {
      //   fetchGetPack(info?.node?.packIDs); //获取标包
      // }
    } else {
      setSelectKeys(selectedKey);
      setTableDataSource([]);
      setSelectedRows([]);
      setSelectedRowKeys([]);
    }
  };

  /** Tree组件的check方法 */
  const onCheck: TreeProps['onCheck'] = (checkedKeys, info) => {};

  const PlanIdsMemo = useMemo(() => {
    const row = selectedRows?.map((item) => {
      return { mockID: item?.mockID };
    });
    return row;
  }, [selectedRows]);

  /** 处理树数据 */
  const orgTreeData = (data: any[]): any[] => {
    return data?.map((item: any) => {
      const titleTree = (
        <Row style={{ width: '100%' }}>
          <Col span={16}>
            <div style={{ fontSize: 16, color: '#7b7b7b' }}>{item?.projectCode || '--'}</div>
          </Col>
          <Col span={8}>
            <div style={{ fontWeight: 600, textAlign: 'right' }}>{item?.projectSum || '--'}</div>
          </Col>
          <Col span={24}>
            <div style={{ fontSize: 16, marginTop: 15 }}>{item?.projectName || '--'}</div>
          </Col>
        </Row>
      );

      return {
        ...item,
        title: (
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              margin: '5px 0',
              padding: '5px',
              borderRadius: 7,
              background: '#f5f4f4',
              position: 'relative',
            }}
            id={item?.id}
          >
            <Tooltip title={item?.projectCode ? tooltipLength(item?.projectCode, 25) : undefined}>{titleTree}</Tooltip>
            {PlanIdsMemo?.find((ite) => ite?.mockID == item?.mockID) ? (
              <a style={{ paddingLeft: 10, position: 'absolute', right: 0, bottom: 0 }}>
                <MyIcon type="icon-xuanzejiaobiao" style={{ fontSize: '50px' }} />
              </a>
            ) : null}
          </div>
        ),
        searchTitle: item?.projectName,
        key: item?.mockID,
        value: item?.projectCode,
        label: item?.projectName,
      };
    });
  };

  /** 树展开方法 */
  const onTreeExpand = (e: any) => {
    setTypeTreeSearchObj({
      ...typeTreeSearchObj,
      expandedKeys: e,
    });
  };

  /** 异步请求数据 */
  const fetchGetApplySev = () => {
    let { current, pageSize, total }: Record<string, any> = getProjectPagination;
    if (ProjectData?.length < total) {
      getProjectRun({
        current,
        pageSize: pageSize + 10,
      });
    }
  };

  /** <<<====================左侧END========================>>> */

  // 加载完成后，默认选中第一条数据 && 获取第一条数据下的标包；
  // 设置flag（defaultSelected），下拉加载时不会重复触发 ，只会执行一次；
  // const [defaultSelected, setDefaultSelected] = useState(false);
  // useEffect(() => {
  //   if (selectKeys.length > 0) return;
  //   if (!getProjectLoading && !defaultSelected) {
  //     setDefaultSelected(true);
  //     if (ProjectData?.length > 0) {
  //       setSelectKeys([ProjectData[0]?.id]);
  //       const item = ProjectData[0];
  //       const temp = item?.mpurchasePacks && item?.mpurchasePacks?.length ? item?.mpurchasePacks?.map((item) => item?.id)?.join(',') : null;
  //       fetchGetPack(temp); // 获取标包
  //     }
  //   }
  // }, [getProjectLoading]);

  return (
    <OneModal
      open={true}
      getContainer={false}
      ref={projectRef}
      title={'项目资金'}
      width={1400}
      onCancel={onClose as any}
      onOk={onConfirm}
      centered
      bodyStyle={{
        padding: 10,
        height: 600,
        display: 'flex',
        flexDirection: 'column',
        overflow: 'hidden',
      }}
    >
      <Row className={`${prefixCls}-RowsBox`}>
        {/* 左侧采购选择列表 */}
        <Col span={7}>
          <Spin spinning={getProjectLoading}>
            <Card
              className={`${prefixCls}-plan-list`}
              title={
                <>
                  <AutoComplete
                    style={{ width: '100%' }}
                    options={autoCompleteOptions}
                    notFoundContent={<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                    // onSelect={onAutoSelectLeft}
                  >
                    <Input placeholder="请按名称搜索" suffix={<SearchOutlined />} onChange={onInputChange} value={typeTreeSearchObj?.searchValue || ''} />
                  </AutoComplete>
                </>
              }
              bodyStyle={{ padding: '2px', overflow: 'hidden' }}
            >
              <div className={pageStyles['InfiniteScrollView']}>
                <InfiniteScroll
                  pageStart={1}
                  className="InfiniteScrollDiv"
                  useWindow={false}
                  initialLoad={false}
                  loadMore={fetchGetApplySev}
                  hasMore={!getProjectLoading}
                  style={{ padding: 8 }}
                >
                  {ProjectData?.length === 0 ? (
                    <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无数据" />
                  ) : (
                    <Tree
                      className={`${prefixCls}-plan-list-TreeCpt`}
                      onSelect={(item: SetStateAction<Key[]>, info) => onChangeSelect(item, info)}
                      blockNode={true}
                      onCheck={onCheck}
                      treeData={orgTreeData(ProjectData || [])}
                      selectedKeys={selectKeys}
                      expandedKeys={typeTreeSearchObj?.expandedKeys}
                      defaultExpandParent={true}
                      checkable={false}
                      onExpand={onTreeExpand}
                    />
                  )}
                </InfiniteScroll>
              </div>
            </Card>
          </Spin>
        </Col>
        <Col span={17}>
          <Spin spinning={false}>
            <div className={'list-table selectPackageTable'}>
              <Table
                size="small"
                bordered={true}
                scroll={{ x: 800, y: 'auto' }}
                style={{ margin: '0' }}
                dataSource={tableDataSource}
                rowSelection={{
                  selectedRowKeys,
                  onChange: (selectedRowKeys: React.Key[], selectedRows: Record<string, any>[]) => {
                    setSelectedRowKeys(selectedRowKeys);
                    setSelectedRows(selectedRows);
                  },
                  type: 'radio',
                  getCheckboxProps: (record) => ({
                    /** 如果当前标包在变更中就不可选 */
                    disabled: record?.changeFlag ? true : false,
                  }),
                }}
                columns={MothedChangeColumns()}
                pagination={false}
                loading={getPackLoading}
                onRow={(record) => {
                  return {
                    onClick: () => {
                      if (!record?.changeFlag) {
                        setSelectedRowKeys([record?.id]);
                        setSelectedRows([record]);
                      }
                    },
                  };
                }}
                rowKey={'id'}
              />
            </div>
          </Spin>
        </Col>
      </Row>
    </OneModal>
  );
};
